package com.liangdemo.web.thread;

/**
 * 5.31日考试
 * 两个线程交替打印1-100
 */
public class ThreadDemo0531 extends Thread {
    public String name;

    ThreadDemo0531(String name) {
        this.name = name;
    }

    static int tick = 1;
    static Object ob = new Object();//创建一个公共资源

    public void ticket() {
        System.out.println(name + " " + tick);
        tick++;

    }

    public void run() {
        while (tick < 101) {
            synchronized (ob) {
                if (tick < 101) {
                    ticket();
                }
            }
            try {
                Thread.sleep(50);
            } catch (Exception e) {
            }
        }
    }


    public static void main(String[] args) {
        ThreadDemo0531 t1 = new ThreadDemo0531("线程1");
        t1.start();
        ThreadDemo0531 t2 = new ThreadDemo0531("线程2");
        t2.start();
    }
}